package campus.aiit.ssl.controller;

import campus.aiit.ssl.domain.model.Instruct;
import campus.aiit.ssl.domain.model.InstructTemplate;
import campus.aiit.ssl.service.InstructService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.lang.NonNull;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author ihaokun
 * @date 2019/12/5 16:00
 */
@Api(description = "指令相关Api")
@RestController
public class InstructController {
  @Resource
  private InstructService instructService;

  /*@Deprecated@SuppressWarnings("无存在必要，Spring Internal View Resolver可以直接进行文件下载，/instructions-devices-template.csv")
  // @GetMapping("templates/download")
  public void downloadTemplate(HttpServletResponse resp){
    try {
      ServletOutputStream os = resp.getOutputStream();
      // byte[] bytes = Files.readAllBytes(Paths.get("src/main/resources/static/instructions-devices-template.csv"));
      byte[] bytes = Files.readAllBytes(Paths.get(URI.create("http://127.0.0.1:8080/template.csv")));
      os.write(bytes);
      resp.setContentType("application/force-download");
      resp.setHeader("Content-Disposition", "attachment; filename=InstructTemplate.csv");
      resp.flushBuffer();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }*/
  //FIXME Unique这种返回的错误说明不易于理解，需要修改错误说明
  @ApiOperation("指令模板（添加）")
  @PostMapping("templates/upload/{name}")
  public boolean uploadTemplate(@PathVariable String name, @RequestPart Part part) throws Exception {
    //FIXED name 可以为null，需要检查
    // check name not equal to ""
    // if (name.isEmpty()) throw new Exception("name不允许为\"\"");
    return instructService.uploadTemplate(name, part);
  }

  @ApiOperation("指令模板（列表）")
  @GetMapping("templates")
  public InstructTemplate[] templates(){
    return instructService.templates();
  }

  @ApiOperation("指令（列表）")
  @GetMapping("templates/{templateId}/instructs")
  public Instruct[] instructs(@PathVariable long templateId){
    return instructService.instructs(templateId);
  }

  @ApiOperation("指令模板（修改）")
  @PutMapping("templates/{id}/{name}")
  public boolean modifyTemplate(@PathVariable long id, @PathVariable String name){
    return instructService.modifyTemplate(id, name);
  }

  // @DeleteMapping("templates/{id}")
  @ApiOperation("指令模板（删除）")
  @DeleteMapping("templates")
  public boolean deleteTemplate(long id){
    return instructService.removeTemplate(id);
  }
}